package com.sxyc.weixin.controller;


import java.text.SimpleDateFormat;
import java.util.Date;

import org.eclipse.jetty.util.UrlEncoded;

import com.amitek.service.bean.protocol.PosInfo;
import com.amitek.service.bean.protocol.TrackInfo;
import com.amitek.service.bean.response.TrackStatus;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.sxyc.tintin.controller.CommonController;
import com.sxyc.tintin.model.DeviceBinding;
import com.sxyc.tintin.model.WxUser;
import com.sxyc.tintin.sdk.SDKUtils;
import com.sxyc.utils.QMapUtils;
import com.sxyc.utils.WeixinUtil;

public class WeixinfindCarController extends Controller{// 使用jFinal 日志
	private static com.jfinal.log.Log log = com.jfinal.log.Log.getLog(CommonController.class);
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/**
 * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
 * ApiConfig 属性值
 */
public ApiConfig getApiConfig() {
    return WeixinUtil.getApiConfig();
}


public void index(){
	String code = getPara("code");
	String openId = (String) getRequest().getSession().getAttribute("openId");
	if(openId == null && code == null){
		String url = SnsAccessTokenApi.getAuthorizeURL(getApiConfig().getAppId(),PropKit.get("domain")+"/findcar", true);
		redirect(url);
	}else{
		if(openId == null){
			SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(getApiConfig().getAppId(), getApiConfig().getAppSecret(),code);
			openId = accessToken.getOpenid();
			getRequest().getSession().setAttribute("openId", openId);
		}
		DeviceBinding user = DeviceBinding.dao.getWxUserByOpenId(openId);
		if(user==null){
			renderJsp("bind.jsp");
		}else{
			sendDeviceStatus(openId);
		}
	}
}

/**
 * 发送设备最后状态（微信找车）
 * @param openId 微信唯一标识
 * @return
 */
public void sendDeviceStatus(String openId){
	PosInfo posInfo = null;
	TrackInfo trackInfo = null;
	Date lastTime = new Date();
	String latlng = "";
	String message = "";
	String address = "";
	String stopPic = "";
	String maplink = "";
	String lastTimeStr = "";
	try {
		Long deviceId = WxUser.dao.getDeviceIdByOpenId(openId);
		if(deviceId!=null){
			TrackStatus trackStatus = SDKUtils.getLastTrackStatus(deviceId);
			System.out.println(trackStatus);
			if (trackStatus != null) {
				stopPic = trackStatus.stopPic;
				posInfo = trackStatus.posInfo;
				trackInfo = trackStatus.trackInfo;
				if(trackInfo!=null){
					lastTime = new Date(trackInfo.gatherTime);
				}else{
					log.info("未查询到设备 [ "+deviceId+" ] 的最后行程信息!");
				}
				if (posInfo != null) {
					double latitude = posInfo.latitude;
					double longitude = posInfo.longitude;
					latlng = latitude +","+longitude;
					// 调用百度或者腾讯地图获取位置信息
					address = QMapUtils.getAddress(latitude, longitude);
				}else{
					log.info("未查询到设备 [ "+deviceId+" ] 最后的位置信息!");
				}
				
				if (address == null || "".equals(address)) {
					address = "暂时无法获取地理位置信息";
				}
				lastTimeStr = sdf.format(lastTime);
				
				//如果都为空
				if("".equals(address)&&"".equals(lastTimeStr)&&"".equals(stopPic)){
					log.info("查询到设备的最后行程信息 [ 地点、时间、图片  ] 均为空!");
					message = "未查询到该设备的最后行程信息！";
				}else{
					maplink = "http://apis.map.qq.com/uri/v1/marker?marker=coord:"+latlng+";title:"+UrlEncoded.encodeString(address)+";addr:"+UrlEncoded.encodeString(address)+"&referer=myapp";
				}
			}else{
				log.info("未查询到设备 [ "+deviceId+" ] 的最后行程信息!");
				message = "未查询到该设备的最后行程信息！";
			}
		}else{
			log.info("微信 [ "+openId+" ] 还未绑定设备!");
			message = "您还未绑定设备！";
		}
	} catch (Exception e) {
		log.error("查找微信 [ "+openId+" ] 绑定的设备最后状态异常，原因："+e.getMessage());
		message = "查找设备最后状态失败，请重试！";
		this.setAttr("latlng", latlng);
		this.setAttr("stopPic", stopPic);
	}
	this.setAttr("maplink", maplink);
	this.setAttr("latlng", latlng);
	this.setAttr("address", address);
	this.setAttr("lastTimeStr", lastTimeStr);
	this.setAttr("stopPic", stopPic);
	message = "【您的爱车最新信息】\n latlng："+latlng+" \n 位置："+address+" \n 时间："+lastTimeStr +" \n 图片："+stopPic;
	System.out.println("message : " + message);
	renderJsp("findCar.jsp");
}
}
